package com.suning.park.admin.mgr.coupon.service.impl;

import com.suning.park.admin.bean.CouponExp;
import com.suning.park.admin.databasespec.dao.SpecCouponMapper;
import com.suning.park.admin.databasespec.dao.SpecCouponUserMapper;
import com.suning.park.admin.enums.ActionStateEnum;
import com.suning.park.admin.enums.YesOrNoEnum;
import com.suning.park.admin.mgr.coupon.service.ICouponService;
import com.suning.park.admin.util.DateUtil;
import com.suning.park.admin.util.IdBuilder;
import com.suning.park.admin.util.StringUtil;
import com.suning.park.admin.util.page.PageInfo;
import com.suning.park.dto.dao.CouponMapper;
import com.suning.park.dto.dao.CouponUserMapper;
import com.suning.park.dto.model.Coupon;
import com.suning.park.dto.model.CouponExample;
import com.suning.park.dto.model.CouponUser;
import com.suning.park.dto.model.SysUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 优惠券管理
 * Created by Administrator on 2017/1/16.
 */
@Service(value="couponService")
public class CouponServiceImpl implements ICouponService {
    private final static Logger logger = LoggerFactory.getLogger(CouponServiceImpl.class);

    @Autowired
    CouponMapper couponMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Autowired
    SpecCouponMapper specCouponMapper;
    @Autowired
    SpecCouponUserMapper specCouponUserMapper;
    /**
     * 增加优惠券
     * @param couponExp
     * @param sysUser
     * @throws Exception
     */
    @Transactional
    @Override
    public void add(CouponExp couponExp,SysUser sysUser) throws Exception{
        Coupon coupon = createModel(couponExp,sysUser);
        validate(coupon);
        coupon.setId(IdBuilder.getID());
        couponMapper.insertSelective(coupon);
    }

    /**
     * 修改优惠券
     * @param couponExp
     * @param sysUser
     * @throws Exception
     */
    @Transactional
    @Override
    public void edit(CouponExp couponExp,SysUser sysUser) throws Exception{
        logger.info("=======couponExp========{}",couponExp);
        if(!StringUtil.isNotBlank(couponExp.getId())){
            throw new Exception("优惠券Id不能为空");
        }
        Coupon coupon = createModel(couponExp,sysUser);
        validate(coupon);
        couponMapper.updateByPrimaryKey(coupon);
    }

    /**
     * 查询优惠券详情
     * @param id
     * @throws Exception
     */
    @Override
    public Coupon selectCouponById(String id) throws Exception{
        logger.info("=======id========{}",id);
        if(!StringUtil.isNotBlank(id)){
            throw new Exception("优惠券Id不能为空");
        }
        return couponMapper.selectByPrimaryKey(id);
    }

    /**
     * 活动广场id查询优惠券列表
     * @param parkId
     * @return
     * @throws Exception
     */
    @Override
    public List<Coupon> selectCouponByParkId(String parkId) throws Exception {
        logger.info("=======parkId========{}",parkId);
        CouponExample example = new CouponExample();
        if(StringUtil.isNotBlank(parkId)){
            example.createCriteria().andParkIdEqualTo(parkId);
        }
        return couponMapper.selectByExample(example);
    }

    /***
     * 查询优惠券列表
     * @param map
     */
    @Override
    public PageInfo selectByPage(Map map, PageInfo page){
        logger.info("=======map========{}",map);
        CouponExample example = new CouponExample();
        CouponExample.Criteria criteria = example.createCriteria();
        if(map.get("parkId") != null && StringUtil.isNotBlank(map.get("parkId").toString())){
            criteria.andIdEqualTo(map.get("parkId").toString());
        }
        if(map.get("startTime") != null && StringUtil.isNotBlank(map.get("startTime").toString())){
            criteria.andStartTimeGreaterThanOrEqualTo(DateUtil.parseDateTime(map.get("startTime").toString(),"yyyy-MM-dd HH:mm:ss"));
        }
        if(map.get("endTime") != null && StringUtil.isNotBlank(map.get("endTime").toString())){
            criteria.andEndTimeLessThanOrEqualTo(DateUtil.parseDateTime(map.get("endTime").toString(),"yyyy-MM-dd HH:mm:ss"));
        }
        if(map.get("couponName") != null && StringUtil.isNotBlank(map.get("couponName").toString())){
            criteria.andCouponNameLike(map.get("couponName").toString());
        }
        if(map.get("state") != null && StringUtil.isNotBlank(map.get("state").toString())){
            criteria.andStateEqualTo(map.get("state").toString());
        }
        criteria.andStateNotEqualTo(ActionStateEnum.DELETE.getValue());
        int total = couponMapper.countByExample(example);
        page.setTotalResult(total);
        example.setLimitStart((page.getCurrentPage()-1) * page.getShowCount());
        example.setLimitRows(page.getShowCount());
        page.setResultObject(couponMapper.selectByExample(example));
        return page;
    }

    /**
     * 优惠券关联用户
     * @param userIds
     * @param couponId
     * @throws Exception
     */
    @Transactional
    @Override
    public void provideCoupon(String userIds,String couponId) throws Exception{
        logger.info("userIds:{},couponId:{}",userIds,couponId);
        if(!StringUtil.isNotBlank(couponId)){
            throw new Exception("优惠券Id不能为空");
        }
        String[] ids = userIds.split(",");
        if(ids.length==0){
            throw new Exception("请选择要绑定优惠券的用户");
        }
        Coupon coupon = couponMapper.selectByPrimaryKey(couponId);
        if(coupon.getUseCount()+ids.length < coupon.getTotal()){
            throw new Exception("超过该优惠券剩余发放数量");
        }
        CouponUser couponUser = new CouponUser();
        couponUser.setId(IdBuilder.getID());
        couponUser.setCreateTime(new Date());
        couponUser.setCouponId(couponId);
        couponUser.setAmount(coupon.getAmount());
        couponUser.setParkId(coupon.getAscription());
        couponUser.setLastTime(new Date());
        couponUser.setCouponName(coupon.getCouponName());
        couponUser.setState(YesOrNoEnum.NO.getValue());
        for(String id : ids){
            couponUser.setSnUserId(id);
            couponUserMapper.insertSelective(couponUser);
            coupon.setUseCount(Integer.valueOf(coupon.getUseCount())+1);
            couponMapper.updateByPrimaryKeySelective(coupon);
        }
    }

    /**
     * 优惠券使用统计
     * @param map
     * @return
     */
    @Override
    public Map statisCoupon(Map map){
//        return specCouponUserMapper.statisCoupon(map);
        return null;
    }

    @Transactional
    @Override
    public void handle(String ids,String type) throws Exception{
        if(!StringUtil.isNotBlank(ids)){
            throw new Exception("优惠券id不能为空");
        }
        if(!StringUtil.isNotBlank(type)){
            throw new Exception("操作类型不能为空");
        }
        Coupon coupon = new Coupon();
        if(ActionStateEnum.NORMAL.getValue().equals(type)){
            coupon.setState(ActionStateEnum.NORMAL.getValue());
        }else if(ActionStateEnum.DELETE.getValue().equals(type)){
            coupon.setState(ActionStateEnum.DELETE.getValue());
        }else if(ActionStateEnum.STOP.getValue().equals(type)){
            coupon.setState(ActionStateEnum.STOP.getValue());
        }
        for(String id : ids.split(",")){
            coupon.setId(id);
            couponMapper.updateByPrimaryKeySelective(coupon);
        }
    }

    @Override
    public Coupon queryCouponById(String id) throws Exception{
        if(!StringUtil.isNotBlank(id)){
            throw new Exception("优惠券id不能为空");
        }
        return couponMapper.selectByPrimaryKey(id);
    }

    private Coupon createModel(CouponExp couponExp,SysUser sysUser) throws Exception{
        Coupon coupon = new Coupon();
        coupon.setUseCount(couponExp.getUseCount());
        coupon.setAscription(couponExp.getAscription());
        coupon.setCouponName(couponExp.getCouponName());
        coupon.setCreateTime(new Date());
        coupon.setLastTime(new Date());
        coupon.setUseCount(0);
        coupon.setParkId(couponExp.getParkId());
        coupon.setAmount(couponExp.getAmount());
        coupon.setRuleDepict(couponExp.getRuleDepict());
        coupon.setTotal(couponExp.getTotal());
        coupon.setRuleType(couponExp.getRuleType());
        coupon.setCreateName(sysUser.getName());
        coupon.setLowestAmount(couponExp.getLowestAmount());
        coupon.setCreateId(sysUser.getUserId());
        coupon.setState(couponExp.getState());
        coupon.setOperatorId(sysUser.getUserId());
        coupon.setOperatorName(sysUser.getName());
        coupon.setStartTime(DateUtil.parseDateTime(couponExp.getStartTimeStr(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
        coupon.setEndTime(DateUtil.parseDateTime(couponExp.getEndTimeStr(),new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));
        return coupon;
    }
    /**
     * 校验字段
     * @param coupon
     * @throws Exception
     */
    public void validate(Coupon coupon) throws Exception{
        if(coupon.getAmount() == null) {
            throw new Exception("优惠券金额不能为空");
        }
        if(coupon.getStartTime() == null){
            throw new Exception("优惠券开始时间不能为空");
        }
        if(coupon.getEndTime() == null){
            throw new Exception("优惠券结束时间不能为空");
        }
        if(coupon.getTotal() == null){
            throw new Exception("优惠券总数量不能为空");
        }
    }

    @Override
    public List<Coupon> selectByParkIdAndUserId(String parkId, String snUserId, String getType) {
        return specCouponMapper.selectByParkIdAndUserId(parkId, snUserId, getType);
    }

    @Override
    @Transactional
    public int add(Coupon coupon){
        return  couponMapper.insert(coupon);
    }

    @Override
    @Transactional
    public int modify(Coupon coupon){
        return  couponMapper.updateByPrimaryKeySelective(coupon);
    }

}
